package cn.neusoft.filter;

import cn.neusoft.vo.ResultBean;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class LoginFilter extends HttpFilter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)req;

        //判断请求路径是否为登录的servlet
        if(request.getRequestURI().contains("/login")){
            chain.doFilter(req, res);
            return;
        }

        //访问登录以外的资源  查询登录状态  所以先获取session
        HttpSession session = request.getSession();
        System.out.println("登录验证："+session.getId());
        //从session中获取adminUser
        Object adminUser = session.getAttribute("adminUser");
        System.out.println("adminUser---"+adminUser);
        //如果adminUser存在 就证明登录过 且没有超时 放行
        if (adminUser!=null){
            chain.doFilter(req, res);
        }else{
            //没有登录过 或登录超时  响应错误码50001
            res.getWriter().write(JSONObject.toJSONString(ResultBean.ERROR(50001,"未登录，请重新登录")));
        }

    }
}
